package com.envy.securityjpa.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 * 使用Key-Value格式传输数据
 * 从登录表单中获取输入的验证码字符串
 * */
@Component
public class VerifyCodeFilter extends GenericFilterBean {
    //设置默认的过滤处理路径，其实就是默认的登录处理路径
    private String defaultFilterProcessUrl = "/goLogin";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())){
            //获取用户通过表单输入的验证码字符串
            String formCaptcha =request.getParameter("code");
            //获取生成的验证码字符串（从session中获取)
            String genCaptcha = (String) request.getSession().getAttribute("verify_code");

            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();

            if(StringUtils.isEmpty(formCaptcha) || StringUtils.isEmpty(genCaptcha)){
                //判断用户输入的验证码是否为空
                out.write(new ObjectMapper().writeValueAsString("验证码不能为空!"));
                out.flush();
                out.close();
                return;
            }
            if(!genCaptcha.toLowerCase().equals(formCaptcha.toLowerCase())){
                //用户输入的验证码和生成的验证码是否一致
                out.write(new ObjectMapper().writeValueAsString("验证码错误!"));
                out.flush();
                out.close();
                return;
            }
        }
        filterChain.doFilter(request,response);
    }
}
